﻿/*
 * Creato da SharpDevelop.
 * Utente: Ciccio
 * Data: 28/12/2009
 * Ora: 18.20
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;

using System.Web.Caching;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft;


namespace ACM.cmsarea08.Controls
{
	public enum DynFields_ValueType {
		json,
		xml
	}
	
	/// <summary>
	/// Description of DynFields.
	/// </summary>
	[DefaultProperty("Text")]
    [ToolboxData("<{0}:DynFields runat=server></{0}:DynFields>")]
	public class DynFields : TextBox
	{
		public DynFields()
		{
		}
		public bool EncodeDecodeValue {
			get {
				object o = ViewState["EncodeDecodeValue"];
				if(o==null) return false;
				return (bool)o;
			}
			set {
				ViewState["EncodeDecodeValue"] = value;
			}
		}			
		
		public override string Text {
			get { 
				//HttpContext.Current.Response.Write("<br>richiesto get:"+base.Text);
				if(this.OutputValueFormat== DynFields_ValueType.json)
					return (EncodeDecodeValue==true?HttpUtility.HtmlEncode(base.Text):base.Text);
				else
					return (EncodeDecodeValue==true?HttpUtility.HtmlEncode(toXml(base.Text)):(toXml(base.Text)));
			}
			set { 
				//HttpContext.Current.Response.Write("<br>richiesto set:"+value);
				
				if(this.InputValueFormat==DynFields_ValueType.json)
					base.Text = (EncodeDecodeValue==true?HttpUtility.HtmlDecode(value):value);
				else
					base.Text = fromXml((EncodeDecodeValue==true?HttpUtility.HtmlDecode(value):(value)));
			//	HttpContext.Current.Response.Write("SETTI :" + base.Text);
			}
		}
		
		public string Value {
			get{ return this.Text;}
			set { this.Text = value;}
		}
		public DynFields_ValueType InputValueFormat {
			get {
				object o = ViewState["_ValueTypes"];
				if(o==null) return DynFields_ValueType.xml;
				return (DynFields_ValueType)o;
			}
			set {
				ViewState["_ValueTypes"] = value;
			}
		}		
		public DynFields_ValueType OutputValueFormat {
			get {
				object o = ViewState["_outValueTypes"];
				if(o==null) return DynFields_ValueType.xml;
				return (DynFields_ValueType)o;
			}
			set {
				ViewState["_outValueTypes"] = value;
				//InputValueFormat  = value;
			}
		}		
		
		public DynFields_ValueType ValueFormat {
			get {
				return OutputValueFormat;
			}
			set {
				OutputValueFormat = value;
				//InputValueFormat  = value;
			}
		}		
		public string UserFields {
			get {
				object o = ViewState["_ufields"];
				if(o==null) return string.Empty;
				return o.ToString();
			}
			set {
				ViewState["_ufields"] = value;
			}
		}
		public string UserFieldsPath {
			get {
				object o = ViewState["_ufieldsp"];
				if(o==null) return string.Empty;
				return o.ToString();
			}
			set {
				ViewState["_ufieldsp"] = value;
			}
		}	
		private string myUserFields {
			get {
				object o = ViewState["_ufields_cc"];
				if(o==null) return string.Empty;
				return o.ToString();
			}
			set {
				ViewState["_ufields_cc"] = value;
			}
		}
		
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);
			string embedobjecturl = "/template/plugins/dynfields/dynfields.js";//Page.ClientScript.GetWebResourceUrl(typeof(EmbedInput), "ACM.cmsarea08.Controls.Resources.EmbedObject.js");
            string cssembedobjecturl = "/template/plugins/dynfields/dynfields.css";//Page.ClientScript.GetWebResourceUrl(typeof(EmbedInput), "ACM.cmsarea08.Controls.Resources.EmbedObject.css");
            if(this.Page is ACM.cmsarea08.Core.MainPage) {
//            	((ACM.cmsarea08.Core.MainPage)this.Page).RegisterMooTools();
                ((ACM.cmsarea08.Core.MainPage)this.Page).RegisterCustomJavascript("/template/plugins/mootools-1.2-core.js");
                ((ACM.cmsarea08.Core.MainPage)this.Page).RegisterCustomJavascript("/template/plugins/mootools-1.2-more.js");
                ((ACM.cmsarea08.Core.MainPage)this.Page).RegisterCustomJavascript(embedobjecturl);
                //((ACM.cmsarea08.Core.MainPage)this.Page).RegisterCustomJavascript(clientobjecturl);
                
                ((ACM.cmsarea08.Core.MainPage)this.Page).RegisterCustomCss(cssembedobjecturl);
            } else {
            	//includi lo script... mootools..
            	if(this.Page.Header!=null) {
            		System.Web.UI.HtmlControls.HtmlHead myhead = this.Page.Header;
					bool foundMo = false;
                    bool foundMoMore = false;
					bool foundEb = false;
                    bool foundEbc = false;
					for(int i = 0; i <myhead.Controls.Count;i++) {
						if(myhead.Controls[i] is LiteralControl) {
                            if (((LiteralControl)myhead.Controls[i]).Text.ToLower().IndexOf("mootools-1.2-core.js") != -1)
                            {
								foundMo=true;
							}
                            if (((LiteralControl)myhead.Controls[i]).Text.ToLower().IndexOf("mootools-1.2-more.js") != -1)
                            {
                                foundMoMore = true;
                            }

							if(((LiteralControl)myhead.Controls[i]).Text.ToLower().IndexOf("dynfield.js")!=-1) {
								foundEb=true;
							}
                            if (((LiteralControl)myhead.Controls[i]).Text.ToLower().IndexOf("dynfield.css") != -1)
                            {
                                foundEbc = true;
                            }

						}
					}
					if(!foundMo) {
                        LiteralControl ct = new LiteralControl("<script language=\"javascript\" type=\"text/javascript\" src=\"/template/plugins/mootools-1.2-core.js\"></script>");
						myhead.Controls.Add(ct);			
					}
                    if (!foundMoMore)
                    {
                        LiteralControl ct = new LiteralControl("<script language=\"javascript\" type=\"text/javascript\" src=\"/template/plugins/mootools-1.2-more.js\"></script>");
                        myhead.Controls.Add(ct);
                    }            		

					if(!foundEb) {
						LiteralControl ct = new LiteralControl("<script language=\"javascript\" type=\"text/javascript\" src=\""+embedobjecturl+"\"></script>");
						myhead.Controls.Add(ct);			
					}
                    if (!foundEbc)
                    {
                        LiteralControl ct = new LiteralControl("<style type=\"text/css\" media=\"screen\">\n"+
                            "<!--\n"+
                            "@import url(\""+cssembedobjecturl+"\");\n"+
                            "-->\n</style>");
                        myhead.Controls.Add(ct);
                    }             		
            		
            	}
            }
            
            //verifica fields:
            if(this.myUserFields==string.Empty) {
	            if(this.UserFields!=string.Empty) {
	            	this.myUserFields = this.UserFields;
	            }
	            if(this.UserFieldsPath!=string.Empty) {
	            	//controlla files
	            	computeFile(this.UserFieldsPath);
	            }
            }
            
        }		
		private void computeFile(string file) {
			if(HttpContext.Current==null) return;
			string _file = HttpContext.Current.Server.MapPath(file);
			if(!System.IO.File.Exists(_file)) return;
			string ext="";
			string finale = "";
			if(_file.LastIndexOf('.')==-1) return;
			ext = _file.Substring(_file.LastIndexOf('.')).ToLower();
			ext = ext.Replace(".","");
			if(ext=="json") {
				//comute json
				finale = readFile(_file);
			}
			if(ext=="xml") {
				//compute xml
				string xml = readFile(_file);
				finale =decodeXml(xml);
			}
			
			if(finale.Trim().Length>0) {
				this.myUserFields = finale;
			}
		}
		
		private string readFile(string file) {
			string testo = "";
			using(System.IO.StreamReader sr = new System.IO.StreamReader(file)) {
				testo = sr.ReadToEnd();
			}
			return testo;
		}
	
       protected override void Render(HtmlTextWriter writer)
        {
			//this.ID
			//this.ClientID
			//this.UniqueID
			writer.Write("<div id=\""+this.ClientID+"_container\" class=\"dynfield\" >");
			//if(EncodeDecodeValue==false)
			base.Render(writer);
			//else {
			//	writer.Write("<input type=\"text\" id=\"" + this.ClientID + "\" name=\"" + this.UniqueID + "\" />");
			//}
			
		    writer.Write("</div>\n");
		    //string shortmonthName = "";string.Join("','",System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat.MonthNames);
		    writer.Write("<script language=\"javascript\" type=\"text/javascript\" defer=\"defer\">\n");
		    writer.Write("window.addEvent('domready', function() {\n");
		    writer.Write("var " + this.ID + "dfields = new DynFields({'istanceid':'"+this.ClientID+"'");
		    string uFields = this.myUserFields;
		    if(uFields.Trim().Length>0) 
		    	writer.Write(",'userfields':" +uFields +" ");
		    writer.Write(",'readformat':'" +this.ValueFormat +"' ");
		    
		    if(EncodeDecodeValue==true && this.Text.Length>0)
		    	writer.Write("\n,'overridevalue':'"+HttpUtility.HtmlDecode(this.Text).Replace("'",@"\'")+"' ");
		    
		    writer.Write("});\n");
		    writer.Write("});");
            writer.Write("</script>\n");
        }
 	
       
       private string fromXml(string testo) {
       	if(string.IsNullOrEmpty(testo)) return "";
       	if(testo.Trim().Length==0) return "";
       	System.Xml.XmlDocument xdoc = null;
       	try {
       		xdoc = new System.Xml.XmlDocument();
       		xdoc.LoadXml(testo.Trim());
       	} catch (Exception ex) {
       		//HttpContext.Current.Response.Write("<br>richiesto set:"+ex.ToString());
       		//this.Controls.Add(new LiteralControl("ERRORE: " + ex.ToString()));
       		//this.Controls.Add(new LiteralControl("ERRORE: " + testo));
       		
       		return testo;}
       	if(xdoc==null) return string.Empty;
       	string result = "";
       	System.Xml.XmlNodeList nodi = xdoc.SelectNodes("//items/item");
       	for(int i = 0 ;i<nodi.Count; i++) {
       		string nome = "";
       		string tipo = "";
       		string valore = "";
       		for(int c = 0;c<nodi[i].ChildNodes.Count;c++) {
       			if(nodi[i].ChildNodes[c].Name.ToLower()=="name") 
       				nome = nodi[i].ChildNodes[c].InnerXml;
       			if(nodi[i].ChildNodes[c].Name.ToLower()=="type") 
       				tipo = nodi[i].ChildNodes[c].InnerXml;
       			if(nodi[i].ChildNodes[c].Name.ToLower()=="value") 
       				valore = nodi[i].ChildNodes[c].InnerXml;
       		}
       		if(nome.Trim().Length==0 || tipo.Trim().Length==0) continue;
       		result+="{\"name\":\""+nome.Trim().Replace("<![CDATA[","").Replace("]]>","")+"\",\"type\":\""+tipo.Trim().Replace("<![CDATA[","").Replace("]]>","")+"\"";
       		if(valore.Length>0) 
       			result+=",\"value\":\""+valore.Trim().Replace("<![CDATA[","").Replace("]]>","")+"\"";
			result+="},";
       	}
       	if(result.EndsWith(",")) result = result.Substring(0,result.Length-1);
       	return "[" + result + "]";
       }
       private string toXml(string testo) {
       	if(string.IsNullOrEmpty(testo)) return "";
       	if(testo.Trim().Length==0) return "";
		string valori = testo;
		//rimuovi gli accapo
		valori = valori.Replace("\n","");
		valori = valori.Replace("\n\r","");
		valori = valori.Replace("\r\n","");
		
		if(valori == string.Empty) {
			return string.Empty;	
		}
		if(valori.StartsWith("[") )
			valori = valori.Substring(1);
		if(valori.EndsWith("]"))
			valori = valori.Substring(0,valori.Length-1);
		string[] valorA = new string[0];
		valorA = System.Text.RegularExpressions.Regex.Split(valori,"},{");
		//object[] jasone = new object[valorA.Length];
		string finalXML = "";
		//HttpContext.Current.Response.Write("ANALISI: " + valorA.Length + ", ");
		System.Xml.XmlNode[] jasone = new System.Xml.XmlNode[valorA.Length];
		for(int i = 0; i<valorA.Length; i ++) {
			if(i==0)
				valorA[i] = valorA[i] + "}";
			else if(i==valorA.Length-1)
				valorA[i] = "{" + valorA[i] ;
			else
				valorA[i] = "{" + valorA[i] + "}";					
			//HttpContext.Current.Response.Write("<br>test: " + valorA[i] + "# ");
			try {
				
				Newtonsoft.Json.Linq.JObject o = Newtonsoft.Json.Linq.JObject.Parse(valorA[i]);
				string _name =o["name"].ToString();
				string _type =o["type"].ToString();
				if(_name.StartsWith("\"")) _name = _name.Substring(1);
				if(_name.EndsWith("\"")) _name = _name.Substring(0,_name.Length-1);
				if(_type.StartsWith("\"")) _type = _type.Substring(1);
				if(_type.EndsWith("\"")) _type = _type.Substring(0,_type.Length-1);
				
				string _value ="";
				if(o.Count>2) {
					_value = o["value"].ToString();
					if(_value.StartsWith("\"")) _value = _value.Substring(1);
					if(_value.EndsWith("\"")) _value = _value.Substring(0,_value.Length-1);
				}
				finalXML += "<item><name><![CDATA[" + _name + "]]></name><type>" + _type +"</type>";
				if(_value.Trim().Length>0) {
					_value =_value.Trim();
					if(_value.StartsWith("[") && _value.EndsWith("]"))
						finalXML += "<value><![CDATA[" + _value+ "]]></value>";
					else {
						if(_value.StartsWith("'")) _value=_value.Substring(1);
						if(_value.EndsWith("'")) _value = _value.Substring(0,_value.Length-1);
						finalXML += "<value><![CDATA[\'" + _value+ "\']]></value>";
					}
						
				}
				finalXML += "</item>";
				//HttpContext.Current.Response.Write("<br>FINLER: " + finalXML + "# ");
				
			} catch (Exception ex) {
				HttpContext.Current.Response.Write("<br>FINLER: " + ex + "# ");
				
				//finalXML +=("FINLER: " + ex + ", ");
			}
		}
		finalXML= "<items>" + finalXML + "</items>";
		return finalXML;		       	
       }
       private string decodeXml(string testo) {
       	if(string.IsNullOrEmpty(testo)) return "";
       	if(testo.Trim().Length==0) return "";
       	System.Xml.XmlDocument xdoc = null;
       	try {
       		xdoc = new System.Xml.XmlDocument();
       		xdoc.LoadXml(testo.Trim());
       	} catch { return string.Empty;}
       	if(xdoc==null) return string.Empty;
       	string result = "";
       	System.Xml.XmlNodeList nodi = xdoc.SelectNodes("//userfields/field");
       	for(int i = 0 ;i<nodi.Count; i++) {
       		string nome = "";
       		string tipo = "";
       		string valore = "";
       		for(int c = 0;c<nodi[i].ChildNodes.Count;c++) {
       			if(nodi[i].ChildNodes[c].Name.ToLower()=="name") 
       				nome = nodi[i].ChildNodes[c].InnerXml;
       			if(nodi[i].ChildNodes[c].Name.ToLower()=="type") 
       				tipo = nodi[i].ChildNodes[c].InnerXml;
       			if(nodi[i].ChildNodes[c].Name.ToLower()=="values") 
       				valore = nodi[i].ChildNodes[c].InnerXml;
       		}
       		if(nome.Trim().Length==0 || tipo.Trim().Length==0) continue;
       		result+="['" + tipo.Trim().Replace("<![CDATA[","").Replace("]]>","") + "', '" + nome.Trim().Replace("<![CDATA[","").Replace("]]>","")+"'";
       		if(valore.Length>0) {
       			if(valore.StartsWith("[") && valore.EndsWith("]"))
       				result+=","+valore.Trim().Replace("<![CDATA[","").Replace("]]>","")+"";
       			else
       				result+=",'"+valore.Trim().Replace("<![CDATA[","").Replace("]]>","")+"'";
       		}
			result+="],";
       	}
       	if(result.EndsWith(",")) result = result.Substring(0,result.Length-1);
       	return "[" + result + "]";
       }

	}
}
